package com.seanzx.dp.serializer.impl;

import com.seanzx.dp.entity.Column;
import com.seanzx.dp.serializer.ISerializer;

import java.io.FilterInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * CHAR: all character is 000 means null. last character is 001 while another is 000 means empty string.
 *       length of characters depends on the column configuration.
 */
public class CharSerializer implements ISerializer {
    @Override
    public String deserialize(Column column, FilterInputStream inputStream) throws IOException {
        byte[] bytes = new byte[column.getLength()];
        inputStream.read(bytes);
        boolean isEmpty = true;
        for (int i = 0; i < bytes.length - 1; i++) {
            if (bytes[i] != '\000') {
                isEmpty = false;
                break;
            }
        }
        if (!isEmpty) {
            return new String(bytes, StandardCharsets.UTF_8);
        }
        if (bytes[bytes.length - 1] == '\000') {
            return null;
        }
        if (bytes[bytes.length - 1] == '\001') {
            return "";
        }
        return new String(bytes, StandardCharsets.UTF_8);
    }

    @Override
    public byte[] serialize(Column column, String value) {
        byte[] bytes = new byte[column.getLength()];
        if (value == null) {
            Arrays.fill(bytes, (byte) '\000');
            return bytes;
        }
        if (value.isEmpty()) {
            for (int i = 0; i < bytes.length - 1; i++) {
                bytes[i] = '\000';
            }
            bytes[bytes.length - 1] = '\001';
            return bytes;
        }
        byte[] bs = value.getBytes(StandardCharsets.UTF_8);
        for (int i = 0; i < bs.length; i++) {
            bytes[i] = bs[i];
        }
        return bytes;
    }

    public static void main(String[] args) {
        String value = "Led Zeppelin";
        byte[] bytes = new byte[30];
        if (value == null) {
            Arrays.fill(bytes, (byte) '\000');
        } else if (value.isEmpty()) {
            for (int i = 0; i < bytes.length - 1; i++) {
                bytes[i] = '\000';
            }
            bytes[bytes.length - 1] = '\001';
        } else {
            byte[] bs = value.getBytes(StandardCharsets.UTF_8);
            for (int i = 0; i < bs.length; i++) {
                bytes[i] = bs[i];
            }
        }

        boolean isEmpty = true;
        for (int i = 0; i < bytes.length - 1; i++) {
            if (bytes[i] != '\000') {
                isEmpty = false;
                break;
            }
        }
        if (!isEmpty) {
            System.out.println(new String(bytes, StandardCharsets.UTF_8));
        }
        else if (bytes[bytes.length - 1] == '\000') {
            System.out.println("null");
        }
        else if (bytes[bytes.length - 1] == '\001') {
            System.out.println("");
        }
    }
}
